<template>
  <div class="AdminNewsShow">
    <h1>AdminNews Show</h1>
    <h1>标题：{{ news.title }}</h1>
    <h1>描述：{{ news.desc }}</h1>
    <div>
      <el-button type="primary" @click="edit"> 编辑 </el-button>
      <el-button type="danger" @click="handleDelete"> 删除 </el-button>
    </div>
  </div>
</template>

<script>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import axios from "axios";
import { ElMessageBox, ElMessage } from "element-plus";

export default {
  name: "AdminNewsShow",
  setup() {
    const route = useRoute();
    const router = useRouter();
    let news = ref({});
    const id = route.params.id;
    const getNews = async () => {
      const res = await axios({ url: `http://localhost:3000/news/${id}` });
      news.value = res.data;
    };

    getNews(); // 获取新闻详情

    const handleEdit = () => {
      router.push({
        name: "AdminNewsEdit",
        params: { id },
      });
    };

    const handleDelete = () => {
      console.log(id);
      ElMessageBox.confirm("你确定要删除此条数据吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await axios({
            method: "DELETE",
            url: `http://localhost:3000/news/${id}`,
          });
          ElMessage({
            type: "success",
            message: "Delete completed",
          });
          // 返回列表
          router.push({ name: "AdminNews" });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "Delete canceled",
          });
        });
    };

    return {
      news,
      edit: handleEdit,
      handleDelete,
    };
  },
};
</script>

<style scoped></style>
